package com.itheima.web;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.sun.corba.se.impl.legacy.connection.USLPort;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        /*//获取username和password
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //将username和password封装到User对象中
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);*/

        //获取所有参数封装到User对象中
        //表单的name属性值必须和对象的属性名相同
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();

        try {
            //BeanUtils.populate(user,map)-->将map集合中的键值对信息封装到对象中
            BeanUtils.populate(user,parameterMap);
            System.out.println(user);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        //调用UserService的login方法
        UserService userService = new UserServiceImpl();
        User user1 = userService.login(user);

        //判断user1是否为null
        if(user1==null){
            //登录失败
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else {
            //登录成功
            //保存用户信息
            request.setAttribute("user",user1);
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
